<template>
  <div class="address-main">
    <el-card
      v-loading="loading"
      shadow="never"
      class="margin-30"
      :body-style="{ padding: '20px' }"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <div slot="header">
        <el-button type="primary" size="mini" @click="showDialog">新增</el-button>
        <el-dialog
          title="地址详情"
          :visible.sync="dialogVisible"
          :before-close="doneDialof"
          width="60%"
        >
          <el-form
            ref="DetailsForm"
            style="padding-left: 30px;"
            :model="addressObj"
            :rules="rules"
            label-width="100px"
            size="mini"
          >
            <el-row :gutter="20">
              <el-col :span="10" :offset="0">
                <el-form-item label="地址名称" prop="addressName">
                  <el-input v-model="addressObj.addressName" placeholder="发货地址名称" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="10" :offset="0">
                <el-form-item label="收货人姓名">
                  <el-input v-model="addressObj.name" placeholder="请输入收货人姓名" clearable />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="10" :offset="0">
                <el-form-item label="收货人手机号" prop="phone">
                  <el-input v-model="addressObj.phone" placeholder="请输入手机号" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="10" :offset="0">
                <el-form-item label="邮政编码" prop="postCode">
                  <el-input v-model="addressObj.postCode" placeholder="请输入邮政编码" clearable />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="10" :offset="0">
                <el-form-item label="收货地址" prop="cityCode">
                  <!-- <el-input v-model="addressForm.cityCode" placeholder="请选择" size="normal" clearable /> -->
                  <el-cascader
                    v-model="selectedOptions"
                    style="width: 100%;"
                    :options="regionData"
                    @change="cascaderChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="10" :offset="0">
                <el-form-item label="详细地址" prop="detailAddress">
                  <el-input v-model="addressObj.detailAddress" placeholder="请输入详细地址" clearable />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <div slot="footer">
            <el-button @click="showDialog">取消</el-button>
            <el-button v-if="addOrupdate" type="primary" @click="getAddAddress">确定</el-button>
            <el-button v-else type="primary" @click="getUpdateAddress">确认更新</el-button>
          </div>
        </el-dialog>
      </div>
      <!-- card body -->
      <template>
        <el-table
          :data="list"
          style="width: 100%"
          border
        >
          <el-table-column
            fixed="left"
            type="index"
            label="#"
            width="50"
            align="center"
          />
          <el-table-column
            prop="addressName"
            label="地址名称"
            width="180"
            align="center"
          />
          <el-table-column
            label="默认发货地址"
            width="180"
            align="center"
          >
            <!-- sendStatus (integer, optional): 默认发货地址：0->否；1->是 -->
            <template slot-scope="scope">
              默认发货地址:
              <el-switch
                v-model="scope.row.sendStatus"
                :active-value="1"
                :inactive-value="0"
                @change="getDefaultAddressChange(scope.row.id,0)"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="收货人姓名"
            width="100"
            align="center"
          />
          <el-table-column
            prop="phone"
            label="收货人电话"
            width="130"
            align="center"
          />
          <el-table-column
            label="收货人地址"
            align="center"
          >
            <template slot-scope="scope">
              <div>
                {{ scope.row.province }}{{ scope.row.city }}{{ scope.row.region }}{{ scope.row.detailAddress }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="receiveStatus"
            label="默认收获地址"
            width="180"
            align="center"
          >
            <!-- receiveStatus (integer, optional): 是否默认收货地址：0->否；1->是 , -->
            <template slot-scope="scope">
              默认收货地址:
              <el-switch
                v-model="scope.row.receiveStatus"
                :active-value="1"
                :inactive-value="0"
                @change="getDefaultAddressChange(scope.row.id,1)"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="180"
            align="center"
          />
          <el-table-column
            fixed="right"
            label="操作"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              <el-button type="text" @click="editAddressDetails(scope.row.id)">编辑</el-button>
              <el-button type="text" style="color: #f00;" @click="getDelAddress(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>

    </el-card>

  </div>
</template>

<script>
import { addressList, setSendOne, AddAddress, companyAddress, update, delAddress, setReceiveOne } from '@/api/allAddress'
// 省市区三级联动
import { regionData, codeToText } from 'element-china-area-data'
export default {
  name: 'OrderAddress',

  data() {
    return {
      loading: true,
      addOrupdate: true,
      list: [],
      dialogVisible: false,
      rules: {},
      regionData,
      selectedOptions: [],
      addressObj: {
        // 'addressName': '',
        // 'city': '',
        // 'cityCode': '',
        // 'detailAddress': '',
        // 'name': '',
        // 'phone': '',
        // 'postCode': '',
        // 'province': '',
        // 'receiveStatus': 0,
        // 'region': '',
        // 'sendStatus': 0
      }
    }
  },

  mounted() {
    this.getAddressList()
  },

  methods: {
    // 删除地址
    getDelAddress(scope) {
      const { id, receiveStatus, sendStatus } = scope
      if (!receiveStatus && !sendStatus) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const res = await delAddress(id)
          const { success, message } = res
          if (success) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getAddressList()
          } else {
            this.$message.error(message)
          }
        })
      } else {
        this.$message('默认地址不允许删除')
      }
    },

    // 编辑地址--更新
    async getUpdateAddress() {
      const res = await update(this.addressObj)
      // console.log(res)
      const { success, message } = res
      if (success) {
        this.$message.success('更新成功')
      } else {
        this.$message.error(message)
      }
    },

    // 地址明细
    async editAddressDetails(id) {
      const res = await companyAddress(id)
      const { success, message, data: { address }} = res
      if (success) {
        this.addOrupdate = false
        this.dialogVisible = true
        this.addressObj = address
        this.selectedOptions = address.cityCode.split(',')
      } else {
        this.$message.error(message)
      }
    },

    // 改变默认 发货/收货 地址
    async getDefaultAddressChange(id, who) {
      let api
      if (who === 0) {
        api = setSendOne
      } else {
        api = setReceiveOne
      }
      const res = await api({ id })
      const { success, message } = res
      if (success) {
        this.getAddressList()
        this.$message.success('修改成功')
      } else {
        this.$message.error(message)
      }
    },

    // 点击新增地址
    async getAddAddress() {
      const res = await AddAddress(this.addressObj)
      console.log(res)
      const { success, message } = res
      if (success) {
        this.dialogVisible = false
        this.$message.success('添加成功')
        // 成功之后重置表单数据
        this.doneDialof()
        this.getAddressList()
      } else {
        this.$message.error(message)
      }
    },

    // 当地址三级联动改变时
    cascaderChange(e) {
      this.addressObj.province = codeToText[e[0]]
      this.addressObj.city = codeToText[e[1]]
      this.addressObj.region = codeToText[e[2]]
      this.addressObj.cityCode = e.join(',')
    },

    // 控制新增输入框显示
    showDialog() {
      this.doneDialof()
    },
    // dialof显示前的回调
    doneDialof() {
      const isShow = this.dialogVisible
      if (isShow) {
        this.dialogVisible = false
      } else {
        this.dialogVisible = true
      }
      // 这是利用vue示例上的更新前的数据进行再次赋值--还原成默认值
      this.addressObj = this.$options.data().addressObj
      this.selectedOptions = this.$options.data().selectedOptions
    },

    // 获取地址列表
    async getAddressList() {
      const res = await addressList()
      // console.log(res)
      const { success, data: { items }, message } = res
      if (success) {
        this.list = items
        this.loading = false
      } else {
        this.$message.error(message)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
